package class61To70;

import java.io.*;


// https://www.luogu.com.cn/problem/P2910

public class Floyd {

    public static int MAX_N = 101;

    public static int MAX_M = 10001;

    public static int[] path = new int[MAX_M];

    public static int[][] distance = new int[MAX_N][MAX_N];

    public static int n, m;

    public static void build() {
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                distance[i][j] = Integer.MAX_VALUE;
            }
        }
    }

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StreamTokenizer in = new StreamTokenizer(br);
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        while (in.nextToken() != StreamTokenizer.TT_EOF) {
            n = (int) in.nval;
            in.nextToken();
            m = (int) in.nval;
            for (int i = 0; i < m; i++) {
                in.nextToken();
                path[i] = (int) in.nval - 1;
            }
            build();
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    in.nextToken();
                    distance[i][j] = (int) in.nval;
                }
            }
            floyd();
            int ans = 0;
            for (int i = 1; i < m; i++) {
                ans += distance[path[i - 1]][path[i]];
            }
            out.println(ans);
        }
        out.flush();
        out.close();
        br.close();
    }

    private static void floyd() {
        for (int mid = 0; mid < n; mid++) {
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < n; j++) {
                    if (distance[i][mid] != Integer.MAX_VALUE &&
                            distance[mid][j] != Integer.MAX_VALUE &&
                            distance[i][j] > distance[i][mid] + distance[mid][j]) {
                        distance[i][j] = distance[i][mid] + distance[mid][j];
                    }
                }
            }
        }
    }
}
